﻿using AspectCore.DynamicProxy;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileSystemGlobbing.Internal;
using Refit;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Service.Core.Redis.Aop
{
    /// <summary>
    /// 默认拦截器
    /// </summary>
    public class DefaultInterceptor : AbstractInterceptorAttribute
    {
        /// <summary>
        /// 默认key
        /// </summary>
        /// <param name="context"></param>
        /// <param name="key"></param>
        /// <param name="parameterNames"></param>
        /// <param name="parameterType"></param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException"></exception>
        protected static string GetDefaultKey(AspectContext context, string key , string[]? parameterNames = null, Type? parameterType = null)
        {
            if (parameterNames is not null && parameterType is not null)
            {
                var parameter = context.Parameters.FirstOrDefault(parameterType.IsInstanceOfType);
                if (parameter is null)
                {
                    throw new ArgumentNullException(nameof(parameterType));
                }
                foreach (var parameterName in parameterNames)
                {
                    key += GetNestedPropertyValue(parameter, parameterName);
                }
            }
            //加入模板替换
            var httpContextAccessor = context.ServiceProvider.GetService<IHttpContextAccessor>();
            if (httpContextAccessor != null)
            {
                var userId = httpContextAccessor.HttpContext?.User?.FindFirst("sub")?.Value;
                string id = string.IsNullOrWhiteSpace(userId)
                    ? ""
                    : userId;

                var tenantId = httpContextAccessor.HttpContext?.User?.FindFirst("tenant_id")?.Value;
                tenantId = string.IsNullOrWhiteSpace(tenantId)
                    ? ""
                    : tenantId;
                return key.Replace("{userId}", id).Replace("{tenantId}", tenantId);
            }
            return key;
        }


        public static string GetNestedPropertyValue(object obj, string propertyPath)
        {
            // 分割属性路径为单独的属性名
            var properties = propertyPath.Split('.');

            // 从根对象开始
            var currentObj = obj;

            foreach (string property in properties)
            {
                if (currentObj == null) return null; // 如果任何中间对象为null，则返回null

                // 获取当前级别的属性
                PropertyInfo propInfo = currentObj.GetType().GetProperty(property);
                if (propInfo == null) throw new ArgumentException($"Property '{property}' not found.");

                // 更新当前对象到下一级
                currentObj = propInfo.GetValue(currentObj, null);
            }

            return currentObj?.ToString();
        }

        public async override Task Invoke(AspectContext context, AspectDelegate next)
        {
            return;
        }
    }
}
